<template>
	<view class="chat-ai-container">
		<!-- #ifdef H5 -->
		<!-- 使用 iframe 嵌入完整聊天界面 -->
		<view v-if="currentMode === 'iframe'" class="iframe-wrapper">
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-container">
				<view class="loading-spinner"></view>
				<text class="loading-text">正在加载智能客服...</text>
				<text class="loading-url">{{ iframeUrl }}</text>
			</view>
			
			<!-- 错误提示 -->
			<view v-if="error" class="error-container">
				<view class="error-icon">❌</view>
				<text class="error-title">加载失败</text>
				<text class="error-message">{{ errorMessage }}</text>
				<button class="retry-button" @click="retryLoad">重试</button>
				<button class="switch-button" @click="switchToBubble">切换到悬浮按钮模式</button>
			</view>
			
			<!-- iframe -->
			<iframe 
				v-show="!loading && !error"
				:src="iframeUrl" 
				class="chat-iframe"
				frameborder="0"
				allow="microphone"
				@load="handleIframeLoad"
				@error="handleIframeError"
			></iframe>
		</view>
		
		<!-- 使用悬浮按钮模式 -->
		<view v-else class="bubble-mode">
			<view class="guide-text">
				<view class="guide-icon">💬</view>
				<text class="guide-title">智能客服助手</text>
				<text class="guide-desc">{{ bubbleLoaded ? '点击右下角的蓝色按钮开始对话' : '正在加载聊天按钮...' }}</text>
				<text v-if="!bubbleLoaded" class="guide-note">如果长时间未出现按钮，请检查网络连接</text>
			</view>
		</view>
		<!-- #endif -->
		
		<!-- #ifndef H5 -->
		<!-- 非 H5 环境使用 web-view -->
		<web-view :src="webviewUrl" @message="handleMessage"></web-view>
		<!-- #endif -->
	</view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// 定义组件 props
const props = defineProps({
	// Dify token
	token: {
		type: String,
		default: 'i1LpZ1l6t3c8hVYp'
	},
	// 显示模式：'iframe' 为嵌入模式（推荐），'bubble' 为悬浮按钮模式
	mode: {
		type: String,
		default: 'iframe',
		validator: (value) => ['iframe', 'bubble'].includes(value)
	},
	// 输入参数
	inputs: {
		type: Object,
		default: () => ({})
	},
	// 系统变量
	systemVariables: {
		type: Object,
		default: () => ({})
	},
	// 用户变量
	userVariables: {
		type: Object,
		default: () => ({})
	}
})

// iframe URL
const iframeUrl = ref('')

// 状态管理
const loading = ref(true)
const error = ref(false)
const errorMessage = ref('')
const bubbleLoaded = ref(false)
const currentMode = ref(props.mode)

// #ifdef H5
// H5 环境下直接加载 Dify 聊天机器人脚本
onMounted(() => {
	if (currentMode.value === 'iframe') {
		// iframe 模式：构建嵌入式聊天 URL
		buildIframeUrl()
		// 设置超时检测
		setTimeout(() => {
			if (loading.value) {
				error.value = true
				errorMessage.value = '加载超时，请检查网络连接或 token 是否正确'
				loading.value = false
			}
		}, 15000) // 15秒超时
	} else {
		// 悬浮按钮模式：加载脚本
		loadDifyChatbot()
	}
})

onUnmounted(() => {
	// 清理脚本（仅悬浮按钮模式）
	if (currentMode.value === 'bubble') {
		const script = document.getElementById(props.token)
		if (script) {
			script.remove()
		}
		// 清理配置
		if (window.difyChatbotConfig) {
			delete window.difyChatbotConfig
		}
	}
})

// iframe 加载完成
const handleIframeLoad = () => {
	console.log('iframe 加载完成')
	loading.value = false
	error.value = false
}

// iframe 加载错误
const handleIframeError = () => {
	console.error('iframe 加载失败')
	loading.value = false
	error.value = true
	errorMessage.value = '无法加载聊天界面，请检查网络连接'
}

// 重试加载
const retryLoad = () => {
	loading.value = true
	error.value = false
	errorMessage.value = ''
	buildIframeUrl()
}

// 切换到悬浮按钮模式
const switchToBubble = () => {
	currentMode.value = 'bubble'
	loading.value = false
	error.value = false
	loadDifyChatbot()
}

const buildIframeUrl = () => {
	// 获取用户信息
	let userInfo = null
	try {
		userInfo = uni.getStorageSync('userInfo')
	} catch (e) {
		console.log('获取用户信息失败', e)
	}
	
	// 构建 iframe URL
	// Dify 的嵌入式聊天 URL 格式：https://udify.app/chatbot/{token}
	let url = `https://udify.app/chatbot/${props.token}`
	
	// 添加查询参数
	const params = new URLSearchParams()
	
	// 添加用户信息
	if (userInfo) {
		if (userInfo.id) params.append('user_id', userInfo.id.toString())
		if (userInfo.nickname || userInfo.username) {
			params.append('user_name', userInfo.nickname || userInfo.username)
		}
		if (userInfo.avatar) params.append('avatar_url', userInfo.avatar)
	}
	
	// 添加自定义参数
	Object.keys(props.systemVariables).forEach(key => {
		params.append(key, props.systemVariables[key])
	})
	
	Object.keys(props.userVariables).forEach(key => {
		params.append(key, props.userVariables[key])
	})
	
	const queryString = params.toString()
	if (queryString) {
		url += `?${queryString}`
	}
	
	iframeUrl.value = url
	console.log('聊天机器人 URL:', url)
}

const loadDifyChatbot = () => {
	// 尝试获取用户信息
	let userInfo = null
	try {
		userInfo = uni.getStorageSync('userInfo')
	} catch (e) {
		console.log('获取用户信息失败', e)
	}
	
	// 设置配置
	window.difyChatbotConfig = {
		token: props.token,
		inputs: {
			...props.inputs
		},
		systemVariables: {
			...(userInfo && userInfo.id ? { user_id: userInfo.id.toString() } : {}),
			...props.systemVariables
		},
		userVariables: {
			...(userInfo ? {
				avatar_url: userInfo.avatar || '',
				name: userInfo.nickname || userInfo.username || ''
			} : {}),
			...props.userVariables
		},
	}
	
	console.log('Dify 配置:', window.difyChatbotConfig)
	
	// 加载外部脚本
	const script = document.createElement('script')
	script.src = 'https://udify.app/embed.min.js'
	script.id = props.token
	script.defer = true
	script.onload = () => {
		console.log('Dify 脚本加载成功')
		// 检测悬浮按钮是否成功创建
		setTimeout(() => {
			const button = document.getElementById('dify-chatbot-bubble-button')
			if (button) {
				bubbleLoaded.value = true
				console.log('悬浮按钮已成功创建')
			} else {
				console.warn('悬浮按钮未找到，可能加载失败')
			}
		}, 2000) // 等待2秒让按钮有时间渲染
	}
	script.onerror = (error) => {
		console.error('Dify 脚本加载失败:', error)
		bubbleLoaded.value = false
	}
	document.body.appendChild(script)
}
// #endif

// #ifndef H5
// 非 H5 环境使用 web-view
const webviewUrl = ref('')

onMounted(() => {
	// 创建一个 HTML 页面的 URL
	// 你需要创建一个静态 HTML 文件或使用在线 HTML 页面
	webviewUrl.value = '/static/chat-ai.html'
})

const handleMessage = (e) => {
	console.log('收到来自 webview 的消息:', e.detail.data)
}
// #endif
</script>

<style lang="scss" scoped>
.chat-ai-container {
	width: 100%;
	height: 100vh;
	background-color: #f5f5f5;
	overflow: hidden;
}

/* #ifdef H5 */
.iframe-wrapper {
	width: 100%;
	height: 100%;
	position: relative;
}

.chat-iframe {
	width: 100%;
	height: 100%;
	border: none;
}

.loading-container {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: white;
	padding: 40rpx;
}

.loading-spinner {
	width: 80rpx;
	height: 80rpx;
	border: 6rpx solid rgba(255, 255, 255, 0.3);
	border-top-color: white;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-bottom: 40rpx;
}

@keyframes spin {
	to { transform: rotate(360deg); }
}

.loading-text {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.loading-url {
	font-size: 24rpx;
	opacity: 0.8;
	text-align: center;
	word-break: break-all;
	padding: 0 40rpx;
}

.error-container {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
	color: white;
	padding: 40rpx;
}

.error-icon {
	font-size: 120rpx;
	margin-bottom: 40rpx;
}

.error-title {
	font-size: 48rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.error-message {
	font-size: 28rpx;
	text-align: center;
	margin-bottom: 40rpx;
	opacity: 0.9;
}

.retry-button,
.switch-button {
	background: white;
	color: #f5576c;
	border: none;
	padding: 20rpx 60rpx;
	border-radius: 50rpx;
	font-size: 28rpx;
	font-weight: bold;
	margin: 10rpx;
	cursor: pointer;
	transition: all 0.3s;
}

.retry-button:hover,
.switch-button:hover {
	transform: scale(1.05);
	box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.2);
}

.switch-button {
	background: rgba(255, 255, 255, 0.2);
	color: white;
}

.bubble-mode {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.guide-text {
	text-align: center;
	color: white;
	padding: 40rpx;
}

.guide-icon {
	font-size: 120rpx;
	margin-bottom: 40rpx;
	animation: bounce 2s infinite;
}

.guide-title {
	display: block;
	font-size: 48rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.guide-desc {
	display: block;
	font-size: 28rpx;
	opacity: 0.9;
	margin-bottom: 20rpx;
}

.guide-note {
	display: block;
	font-size: 24rpx;
	opacity: 0.7;
	margin-top: 20rpx;
}

@keyframes bounce {
	0%, 100% {
		transform: translateY(0);
	}
	50% {
		transform: translateY(-20rpx);
	}
}

/* 自定义聊天机器人悬浮按钮样式 */
:deep(#dify-chatbot-bubble-button) {
	background-color: #1C64F2 !important;
	width: 60px !important;
	height: 60px !important;
	bottom: 20px !important;
	right: 20px !important;
}

:deep(#dify-chatbot-bubble-window) {
	width: min(90vw, 400px) !important;
	height: min(80vh, 600px) !important;
	bottom: 90px !important;
	right: 20px !important;
}
/* #endif */
</style>